package com.cll.learn.cas.demo02;

/**
 * 描述信息:
 *
 * @author CLL
 * @version 1.0
 * @date 2021/5/15 11:09
 */
public class ConsumeThread implements Runnable {

    private final User user;

    public ConsumeThread(User user) {
        this.user = user;
    }

    @Override
    public void run() {
        // 消费200次结束
        for (int i = 0; i < 50; i++) {
            while (true) {
//                System.out.println("===>>> 模拟消费不成功一直消费");
                int stamp = user.getMoney().getStamp();
                Integer currentMoney = user.getMoney().getReference();
                if (currentMoney > 10) {
                    if (user.getMoney().compareAndSet(currentMoney, currentMoney - 10, stamp, stamp+1)) {
                        System.out.println("===>>> 当前用户余额 = " + currentMoney + "：消费成功之后余额 = " + user.getMoney().getReference() + ":版本号 = " + user.getMoney().getStamp());
                        break;
                    } else {
                        System.out.println("===>>> 消费不成功，一直尝试消费");
                    }
                } else {
                    System.out.println("===>>> 余额不足，不能消费");
                    break;
                }
            }

            try {
                Thread.sleep(100);
            } catch (InterruptedException ie) {

            }
        }

    }
}
